# -*- coding:utf-8 -*-
'''
author:***y
time:2019-10-09
主要功能说明：
1、获取登录接口的token
2、根据疾病查询食材

'''
import requests
import csv
import json
import time

class Test_disease_to_food():

    def __init__(self):
        print("-------------测试开始----------------")

    def login_token(self):
        # 初始化登录接口
        login_url = 'https://api.icarbonx.com/oauth2/token?grant_type=password&sms_verify=true'
        login_header = {"Authorization": "Basic Y29tLm1ldW0uY29hY2guaXBob25lOjdmYTYyZmFmYzgxZTgwMzY="}
        login_data = {
            "username": "15112345678",
            "password": "888888",
            "appName": "health-buddy",
            "grant_type": "password",
            "sms_verify": "true"
        }
        # 登录请求接口
        r_login = requests.post(url=login_url,data=login_data,headers=login_header)
        # 获取登录的响应报文
        token = r_login.json()['access_token']
        # print(token)
        '''请求接口获取token值'''
        return token

    def disease_to_food(self):
        # 初始化
        food_flag_init = 0
        food_error_init = 0
        # 开始时间
        start = time.time()

        #读取csv文件，获取msg的入参
        with open('E:\\test\\HB\\askCondition.csv','r') as ac:
            reader = csv.reader(ac)
            #从文本第二行开始读取
            # next(reader)
            for row in reader:
                print(row[0])
                #疾病食材问答接口的请求参数msg
                df_msg = {"msg":row[0]}
                print(df_msg)
                # 获取登录的token
                df_headers = {"Authorization": "Bearer " + self.login_token()}

                # 疾病食材请求的url
                df_url = 'https://api.icarbonx.com/nlp/api/v1.0/disease_to_food'
                #疾病食材请求接口
                r_df = requests.post(url=df_url,headers= df_headers,data=df_msg)
                #获取疾病食材的响应报文
                print(r_df)
                df_response = json.loads(r_df.text)
                print(df_response)
                print(type(df_response))

                #判断响应结果是否为空，则获取text的文本值
                if df_response:
                    print(df_response)
                    food_flag_init = food_flag_init + 1
                    print("疾病食材查询成功%d"%food_flag_init)
                    food_response_all = df_response['text']
                    disease_food = ['df_msg','df_food']
                    #保存响应结果到本地文件
                    with open('E:\\test\\HB\\disease_to_food.csv', 'a+', encoding='utf-8-sig') as dof:
                        disease_food[0] = row[0]
                        #将返回结果中的删除，避免换行
                        print(food_response_all)
                        if '\n' in food_response_all:
                            food_response_all = food_response_all.replace("\n","")

                        disease_food[1] = food_response_all
                        dof.write(','.join(disease_food))
                        dof.write('\n')
                        dof.close()

                else:
                    food_error_init = food_error_init + 1
                    print("疾病食材查询结果为空，可能未识别到疾病名称%d"%food_error_init)
                    with open('E:\\test\\HB\\disease_to_food_fail.csv', 'a+', encoding='utf-8-sig') as doff:
                        food_disease_fail = ['food_msg']
                        food_disease_fail[0] = row[0]
                        doff.write(','.join(food_disease_fail))
                        doff.write('\n')
                        doff.close()
        ac.close()


        print("------疾病食材查询结果统计"+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+"------")
        print("疾病食材查询成功%d" % food_flag_init)
        print("疾病食材查询无结果%d" % food_error_init)
        # 计算花费的时间
        print('cost time:{}'.format(time.time() - start))



if __name__ == '__main__':
    dtf = Test_disease_to_food()
    dtf.disease_to_food()










